package com.qnvip.sbd.mybatis.sqlprovider;

import com.qnvip.sbd.mybatis.util.ObjectStruct;
import com.qnvip.sbd.util.StringUtil;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import static org.apache.ibatis.jdbc.SqlBuilder.*;

public class SqlInsertProvider {

	private Object object = null;

	private Map<String, String> map = new HashMap<String, String>();

	public SqlInsertProvider(Object object) {
		this.object = object;
		BEGIN();
		INSERT_INTO(SqlProviderHelper.getTable(object));
	}

	private void process() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException {
		ObjectStruct objectStruct = new ObjectStruct(object);
		Map<String, Method> getMethods = objectStruct.getGetMethods();
		Field[] fields = object.getClass().getDeclaredFields();
		for (int i = 0; fields != null && i < fields.length; i++) {
			Method getMethod = getMethods.get(fields[i].getName());
			if (getMethod != null) {
				Object childObject = getMethod.invoke(object);
				if (childObject != null) {
					map.put(fields[i].getName(), null);
				}
			}
		}
	}

	public String getInsertStatement() throws IllegalAccessException, IllegalArgumentException,
			InvocationTargetException, IOException {
		if (map.size() == 0) {
			process();
			Iterator<String> itr = map.keySet().iterator();
			while (itr.hasNext()) {
				String key = itr.next();
				VALUES(StringUtil.camelToUnderline(key), "#{" + key + "}");
			}
		}
		String sql = SQL();
		System.out.println(sql);
		return sql;
	}
}
